package com.example.spiders;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import com.example.spiders.dto.Picture;
import com.example.utils.HeaderUtils;
import com.example.utils.HttpClientUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * @author swain
 * @description:
 * @date 2020/12/2
 */
public class SinglePictureDownloader {
    private String referer;
    private CloseableHttpClient httpClient;
    private Picture picture;
    private String filePath;


    public SinglePictureDownloader(Picture picture, String referer, String filePath) {
        this.httpClient = HttpClientUtils.getHttpClient();
        this.picture = picture;
        this.referer = referer;
        this.filePath = filePath;
    }

    public void download() {
        HttpGet get = new HttpGet(picture.getUrl());
        Random rand = new Random();
        //设置请求头
        get.setHeader("User-Agent", HeaderUtils.getRandomHeader());
        get.setHeader("referer", referer);
        System.out.println(referer);
        HttpEntity entity = null;
        try (CloseableHttpResponse response = httpClient.execute(get)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                entity = response.getEntity();
                if (entity != null) {
                    File picFile = new File(filePath, picture.getTitle());
                    try (OutputStream out = new BufferedOutputStream(new FileOutputStream(picFile))) {
                        entity.writeTo(out);
                        System.out.println("下载完毕：" + picFile.getAbsolutePath());
                    }
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

